#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>


int my_sendto(int sockfd,const char* buf,int length,const struct sockaddr* server_addr,socklen_t addrlen){

    int temp=0;
    int ftemp=0;

    while(1){
        
        ftemp=sendto(sockfd,buf+temp,length - temp,0,server_addr,addrlen);//0 阻塞(发送的缓冲区满/网络阻塞);
        if(ftemp == -1){
            perror("my_send err");
            return -1;
        }
        temp+=ftemp;
        if(temp >= length){
            break;
        }
        
    }
    return 0;
}


int main(int argc,char const *argv[]){
    // if(argc < 2){
    //     printf("usage err\n");
    //     return -1;
    // }
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);//ipv4,tcp
    if(sockfd == -1){
        perror("sock err");
        return -1;
    }
    //服务器地址:IP 端口号
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    // server_addr.sin_port =htons(atoi(argv[2]));
    server_addr.sin_port =htons(8888);

    // server_addr.sin_addr.s_addr=inet_addr(argv[1]);
    server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    printf("IP=%s\n",inet_ntoa(server_addr.sin_addr));
    socklen_t addrlen= sizeof(server_addr);
    


    //收发数据
    char buf[64]={0};

    while(1){
        scanf("%s",buf);
        
        if(my_sendto(sockfd,buf,64,(struct sockaddr*)&server_addr,addrlen) == -1){ //send 不一定会一次全部发送完，分多次发送完
            perror("send err");
            break;
        }
        if(strcmp(buf,"quit") == 0){
            printf("sever quit\n");
            break;
        }
    }


    //关闭
    close(sockfd);


    return 0;
}
